package com.smarthealthring.mm.widgets;

import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * Created by sun on 17-11-24.
 * 监听数据是否已填的textview　一般作为保存或下一步按钮使用
 */

public class CheckStatusTextView extends AppCompatTextView {

    private StatusListener mListener;

    private List<ValidStatusObserable> mObserables;

    public CheckStatusTextView(Context context) {
        super(context);
    }

    public CheckStatusTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setListener(StatusListener listener) {
        mListener = listener;
    }

    public void addObserable(ValidStatusObserable... obserables) {
        if (mObserables == null) {
            mObserables = new ArrayList<>();
        }
        mObserables.addAll(Arrays.asList(obserables));
        boolean s = true;
        for (int i = 0; i < mObserables.size(); i++) {
            mObserables.get(i).setListener(new StatusListener() {
                @Override
                public void status(boolean status) {
                    //被观察者状态改变后　更新整体状态
                    boolean s = true;
                    for (int j = 0; j < mObserables.size(); j++) {
                        if (mObserables.get(j).isValid() == false) {
                            s = false;
                        }
                    }
                    mListener.status(s);
                }
            });
            if (mObserables.get(i).isValid() == false) {
                s = false;
            }
        }
        mListener.status(s);
    }

    public void removeObserable(ValidStatusObserable... obserables) {
        if (mObserables != null) {
            mObserables.removeAll(Arrays.asList(obserables));
            boolean s = true;
            for (int i = 0; i < mObserables.size(); i++) {
                if (mObserables.get(i).isValid() == false) {
                    s = false;
                }
            }
            mListener.status(s);
        }
    }

    public interface StatusListener {
        void status(boolean status);
    }

    public interface ValidStatusObserable {

        void setListener(StatusListener listener);

        boolean isValid();
    }

}

